package com.g2.rpc.rpc.client;


import com.g2.rpc.common.serialize.Serialization;
import com.g2.rpc.remoting.Client;
import com.g2.rpc.rpc.Invoker;
import com.g2.rpc.rpc.Response;
import com.g2.rpc.rpc.RpcInvocation;
import com.g2.rpc.rpc.handler.G2ClientHandler;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class G2ClientInvoker implements Invoker {

    private Client client;

    private Serialization serialization;

    public G2ClientInvoker(Client client, Serialization serialization) {
        this.client = client;
        this.serialization = serialization;
    }

    @Override
    public Object invoke(RpcInvocation rpcInvocation) throws Exception{
        byte[] bytes = serialization.serialize(rpcInvocation);
        client.send(bytes);

        CompletableFuture<Response> future = G2ClientHandler.waitResult(rpcInvocation.getId());
        Response response = future.get(60, TimeUnit.SECONDS);
        if (response.success()) {
            return response;
        }
        throw new RuntimeException("server error! 请求：{}，响应：{}");
    }
}
